﻿#region itdc

/************************************************************************
*Copyright(C) 2015 by qsgy
 *All rights reserved. 
 *FileName:     $safeitemname$
 *Author:       oyh
 *Version:      
 *UnityVersion：
 *Date:   $time$      
 *Description:    
 *History: 
************************************************************************/
#endregion
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PosAdapter : MonoBehaviour {
    [Header("Component")]
    [SerializeField, Tooltip("绑定一个对应的显示对象，如果没有绑定则默认为子物体animation")]
    private Transform animat;
    [SerializeField, Tooltip("绑定一个对应的刚体,需要在同一物体下,可以没有刚体")]
    private Rigidbody rig;
    [SerializeField, Tooltip("绑定一个对应的阴影，没有则默认绑定子物体shadow,可以没有阴影")]
    private Transform shadow;
    [Header("state")]
    [SerializeField, Tooltip("影子的z坐标")]
    private float shadowZ;
    [SerializeField, Tooltip("重力加速度")]
    private float gravity;
    [SerializeField, Tooltip("跳跃系数，值越大，跳得越高")]
    public static float jumpK = 1;
    private Vector3 aniLocalPos;//animation的局部坐标
    private Transform selfTrans;
    private delegate void UpdataFunc();//根据获取到的组件来选择刷新的方法
    private UpdataFunc func;


    private void Awake()
    {
        selfTrans = transform;
        animat = selfTrans.Find(Helper.subAnimation);
#if DEBUG
        if (animat == null) Debug.LogError(name + "can't find animation");
#endif
        shadow = selfTrans.Find(Helper.subShadow);
        rig = GetComponent<Rigidbody>();
        func = new UpdataFunc(UpdataAni);
        if (rig != null)
        {
            func += UpdataRig;
        }

        if (shadow != null)
        {
              func += UpdataShadow;
             // shadowZ = animat.position.z- shadow.position.z;//初始化影子z坐标
            //print(shadowZ);
            

        }
 
        aniLocalPos = animat.localPosition;//初始化角色局部坐标。

    }
    private void Start()
    {
        gravity = GameManager.Instance.gravity;//获取重力加速度

    }

    void Update()
    {

        func();//更新角色状态
        //Ray
    }

    /// <summary>
    /// 更新角色显示的位置
    /// </summary>
    void UpdataAni()
    {
        float h = -selfTrans.position.z * jumpK;
        animat.localPosition = aniLocalPos + new Vector3(0, h,0);
        animat.position = new Vector3(animat.position.x, animat.position.y, selfTrans.position.y);
    }

    /// <summary>
    /// 更新角色阴影位置
    /// </summary>
    void UpdataShadow()
    {
        shadow.position = new Vector3(shadow.position.x, shadow.position.y, animat.position.z- shadowZ);//影子位置固定
        
    }

    /// <summary>
    /// 更新角色受到重力
    /// </summary>
    void UpdataRig()
    {
        if (Time.timeScale == 0) return;
        rig.AddForce(new Vector3(0, 0, rig.mass * gravity));//添加重力

    }

}
